package com.turing.procedure.service.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.turing.common.util.StringUtils;
import com.turing.procedure.client.reviewer.ReviewStatisticInnerService;
import com.turing.procedure.model.domain.task.TaskRecord;
import com.turing.procedure.service.task.StatisticService;
import com.turing.procedure.service.task.TaskRecordService;
import com.turing.procedure.vo.in.KeyStatisticSearchVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StatisticServiceImpl implements StatisticService {

    private static final Log logger = LogFactory.getLog(StatisticServiceImpl.class);

    @Autowired
    private ReviewStatisticInnerService reviewStatisticInnerService;

    @Autowired
    private TaskRecordService taskRecordService;

    public Map<String,String> getKeyStatistic(KeyStatisticSearchVO searchVO){

        QueryWrapper<TaskRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",0);


        if (searchVO != null && !StringUtils.isEmpty(searchVO.getTemplateSn())) {
            queryWrapper.eq("template_id",searchVO.getTemplateSn());
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (!StringUtils.isEmpty(searchVO.getDateBegin())) {
                Date begin = format.parse(searchVO.getDateBegin() + " 00:00:00");
                queryWrapper.ge("uploaded_time",begin);
            }
        } catch (Exception e) {
            logger.error(" date parse error..");
        }

        try {
            if (!StringUtils.isEmpty(searchVO.getDateEnd())) {
                Date end = format.parse(searchVO.getDateEnd() + " 23:59:59");
                queryWrapper.le("uploaded_time",end);
            }
        } catch (Exception e) {
            logger.error(" date parse error..");
        }

        long total = taskRecordService.count(queryWrapper);

        List<Integer> statusIn = new ArrayList<>();
        statusIn.add(5);
        statusIn.add(6);
        queryWrapper.in("task_status",statusIn);
        long reviewed = taskRecordService.count(queryWrapper);

        Map<String,String> statisticMap = new HashMap<>();
        statisticMap.put("total",total + "");
        statisticMap.put("reviewed",reviewed + "");

        String correctness = reviewStatisticInnerService.calculateCorrectness(searchVO.getTemplateSn(),searchVO.getEleId(),
                searchVO.getDateBegin(),searchVO.getDateEnd());

        statisticMap.put("correctness",correctness);

        return statisticMap;
    }

    /*
     * 计算图表数据
     * dateType 0周   1月
     * */
    public Map<String,List<Object>> getGraphData(String templateSn,Integer eleId,Integer dateType) throws ParseException{
        Map<String,List<Object>> resultMap = new HashMap<>();
        List<Object> reviewed = new LinkedList<>();
        List<Object> dates = new LinkedList<>();
        List<Object> correctness = new LinkedList<>();

        List<String> dateStr = new LinkedList<>();
        if (dateType == 0) {
            List<String> weeksDateStr = getWeeksDateStr(12);
            dateStr.addAll(weeksDateStr);
        }
        if (dateType == 1) {
            List<String> monthDateStr = getMonthDateStr();
            dateStr.addAll(monthDateStr);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat onlyMD = new SimpleDateFormat("MM-dd");
        SimpleDateFormat onlyMM = new SimpleDateFormat("MM");

        for (String s : dateStr) {
            QueryWrapper<TaskRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_del",0);
            if (!StringUtils.isEmpty(templateSn)) {
                queryWrapper.eq("template_id",templateSn);
            }
            List<Integer> statusIn = new ArrayList<>();
            statusIn.add(5);
            statusIn.add(6);
            queryWrapper.in("task_status",statusIn);

            String[] split = s.split("~");
            String begin = split[0];
            String end = split[1];

            Date beginDate = format.parse(begin);

            queryWrapper.ge("uploaded_time",beginDate);
            Date endDate = format.parse(end);
            queryWrapper.le("uploaded_time",endDate);

            long l = taskRecordService.count(queryWrapper);
            reviewed.add(l);

            if (dateType == 1) {
                dates.add(onlyMM.format(beginDate) + "月");
            } else {
                dates.add(onlyMD.format(beginDate) + "~" + onlyMD.format(endDate));
            }

            String correctRate = reviewStatisticInnerService.calculateCorrectness(templateSn,eleId,begin,end);
            correctness.add(Double.valueOf(correctRate));

        }
        Collections.reverse(dates);
        Collections.reverse(reviewed);
        Collections.reverse(correctness);
        resultMap.put("date",dates);
        resultMap.put("reviewed",reviewed);
        resultMap.put("correctness",correctness);
        return resultMap;
    }

    private List<String> getMonthDateStr(){
        List<String> resultList = new LinkedList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int currentMonth = calendar.get(Calendar.MONTH);
        for (int j = currentMonth; j >= 0; j--) {
            calendar.set(Calendar.DAY_OF_MONTH,1);
            Date begin = calendar.getTime();

            calendar.add(Calendar.MONTH,1);
            calendar.add(Calendar.DAY_OF_YEAR,-1);
            Date end = calendar.getTime();
            resultList.add(format.format(begin) + " 00:00:00" + "~" + format.format(end) + " 23:59:59");
            calendar.add(Calendar.MONTH,-1);
        }

        return resultList;
    }

    private List<String> getWeeksDateStr(int weekNum){
        List<String> resultList = new LinkedList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < weekNum; i++) {
            calendar.set(Calendar.DAY_OF_WEEK,2);
            Date begin = calendar.getTime();

            calendar.set(Calendar.DAY_OF_WEEK,1);
            calendar.add(Calendar.WEEK_OF_YEAR,1);
            Date end = calendar.getTime();

            calendar.add(Calendar.WEEK_OF_YEAR,-2);
            resultList.add(format.format(begin) + " 00:00:00" + "~" + format.format(end) + " 23:59:59");
        }
        return resultList;
    }
}
